var alarmMap = new Map();
var loginName = "";
getCurrentUser();
// 获取用户信息
function getCurrentUser() {
  var userName = "";
  $.ajax({
    url: "/user/get",
    type: "GET",
    async: false,
    success: function (result) {
      console.log(result)
      if (result.status == "200") {
        var userOrgId = result.data.org.id;
        var mapcentrex = result.data.org.centrex;
        var mapcentrey = result.data.org.centrey;
        userName = result.data.name;
        loginName = result.data.loginName;
        userId = result.data.userId;
        var roleId = result.data.role.roleId;
        localStorage.setItem('userOrgId', userOrgId);
        localStorage.setItem('userName', userName);
        localStorage.setItem('mapcentrex', mapcentrex);
        localStorage.setItem('mapcentrey', mapcentrey);
        localStorage.setItem('userId', userId);
        localStorage.setItem('roleId', roleId);
        localStorage.setItem('loginName', loginName);
      } else {

      }
    }

  });

}
//alarmSumFunc();
//未处理报警数渲染
function alarmSumFunc() {
  var alarmSum;
  $.ajax({
    url: '/paging/notdispose/smoke/pageNumber',
    async: false,
    success: function (result) {
      var alarmSum = result.data.总条数;
      console.log(alarmSum)

      $('.indexLeft .alarmSum').text(alarmSum);
      $(".dataStatistics .dataHandleNum").val(alarmSum);
      $('.indexLeft').show();
      $('.indexLeft.untreatedAlarmNum').show();
      if (alarmSum != 0) {
        $('.indexLeft').addClass('move');
        $('.indexLeft.untreatedAlarmNum').addClass('move1');
      } else {
        $('.indexLeft').removeClass('move');
        $('.indexLeft..untreatedAlarmNum').removeClass('move1');
      }
    }
  });
}

//状态转换
function getStatusStr(status) {
  var statusStr = 'normal';
  switch (status) {
    case 1:
      statusStr = "fire"; //火警
      break;
    case 2:
      statusStr = "normal"; //静音
      break;
    case 3:
      statusStr = "malfunction"; //故障
      break;
    case 4:
      statusStr = "lowpower"; //低压
      break;
    case 7:
      statusStr = "normal"; //正常待机
      break;
    case 9:
      statusStr = "normal"; //自检数据上报
      break;


    default:
      break;
  }
  return statusStr;
}
var webhost = location.hostname.toLowerCase();
const ws = new Sockette('ws://' + webhost + ':9091/websocket/signalmonitor/' + loginName, {
  // const ws = new Sockette('wss://' + webhost + '/websocket/signalmonitor/' + loginName, {
  timeout: 5e3,
  maxAttempts: 10,
  onopen: function (e) {
    ws.send('Successful connection!');

  },
  onmessage: function (e) {


    var str = e.data;
    var strs = str.split(",");
    var cmd = strs[0];
    //接收到报警信息
    console.log(str)
    if (cmd == "cmd_sendAlarm") {

      var devCode = strs[1];
      var status = strs[2];
      var statusStr = strs[3];
      var latitude = strs[4];
      var longitude = strs[5];
      var deviceName = strs[6];
      var address = strs[7];
      var returntime = strs[8];
      var linkMain1 = strs[9] ? strs[9] : '';
      var linkPhone1 = strs[10] ? strs[10] : '';
      var linkMain2 = strs[11] ? strs[11] : '';
      var linkPhone2 = strs[12] ? strs[12] : '';
      var linkMain3 = strs[13] ? strs[13] : '';
      var linkPhone3 = strs[14] ? strs[14] : '';
      var linkMain4 = strs[15] ? strs[15] : '';
      var linkPhone4 = strs[16] ? strs[16] : '';
      var alarmId = strs[17];
      var fireCount = strs[18];
      var alarmRadius = strs[19];
      var userOrgId = strs[20];

      if (linkMain1 == 'null') {
        linkMain1 = '';
      }
      if (linkPhone1 == 'null') {
        linkPhone1 = '';
      }
      if (linkMain2 == 'null') {
        linkMain2 = '';
      }
      if (linkPhone2 == 'null') {
        linkPhone2 = '';
      }
      if (linkMain3 == 'null') {
        linkMain3 = '';
      }
      if (linkPhone3 == 'null') {
        linkPhone3 = '';
      }
      if (linkMain4 == 'null') {
        linkMain4 = '';
      }
      if (linkPhone3 == 'null') {
        linkPhone4 = '';
      }
      // var unit = 'unit';
      // var levelisk = 'levelisk';
      // var appearPeople = 'appearPeople';
      // var telephone = 'telephone';
      console.log(localStorage.getItem('userOrgId'), userOrgId, localStorage.getItem('userOrgId') == userOrgId); //66 77
      if (localStorage.getItem('userOrgId') == userOrgId) {

        // -----------如果当前地图展示的当前设备是烟感，则报警-------
        // if (deviceTypeId == 001) {
        if (devTypeId == 'smoke' || devTypeId == 'all' || devTypeId == 1) {
          BaiDuMap.deletePoint(devCode);
          // console.log(fireCount, status, devCode, deviceName, address, latitude, longitude, linkMain1, linkPhone1, linkMain2, linkPhone2, linkMain3, linkPhone3, linkMain4, linkPhone4);
          BaiDuMap.addMarker(fireCount, status, devCode, deviceName, address, latitude, longitude, linkMain1, linkPhone1, linkMain2, linkPhone2, linkMain3, linkPhone3, linkMain4, linkPhone4);
        }

        //设备总数
        devSumFunc();
        // --------------------------------apk报警-------------------
        // cmd_sendAlarm,1001,81,apkAlarm,120.18336,30.2426,应答器,金钱巷微型消防站,2019-03-14 13:53:19,蒋月泉,15858251488,,,,,null,null,121377

        if (status == 1 || status == 81) {
          console.log(status)
          //            	  播放报警声音
          $('.untreatedAlarmNum').show();
          stopSound();
          playSound();
          speach('警报：' + address + deviceName + '烟雾报警');
          //本月报警总数
          thisMonthFunc();

          // 报警管理 首次渲染
          dailyAlarmPageList(dailyAlarmPage);
          //                // 报警管理 获取总页数 点击分页渲染列表
          dailyAlarmSumPage(dailyAlarmPage);
          alarmSumInitFunc();
          // 如果当前地图展示的当前设备是烟感，则定位
          if (devTypeId == 'smoke' || devTypeId == 'all' || devTypeId == 1) {
            BaiDuMap.panTo(latitude, longitude);
            setTimeout(function () {
              BaiDuMap.popMenu(devCode);
            }, 700);
          }
          //                   大数据	七日报警数据图表
          sevenAlarmSumDataRander();
          alarmMap.set(devCode, status);
          newAlarmFn();
          //                alarmHandleNum = smokeAlarmData.length-1;
          // 旧的报警框
          // smokeAlarmDataAjax();
          // alarmHandleNum = 0;
          // smokeAlarmRender(alarmHandleNum);
          $('#smokeAlarm').show();
          alarmpageTurningBtn();

        } else if (status == 81) {

          // 播放报警声音
          $('.untreatedAlarmNum').show();
          stopSound();
          playSound();
          // 刷新报警列表
          newAlarmFn();
        } else {
          alarmMap.delete(devCode);
          if (alarmMap.size == 0) {
            stopSound();
          }
        }
        //        报警数渲染
        devListSum();
      }
      // }



    }
    if (cmd == 'cmd_alarmDispseSync') {
      var alarmId = strs[1];
      // 报警管理 首次渲染
      dailyAlarmPageList(dailyAlarmPage);
      // 报警管理 获取总页数 点击分页渲染列表
      dailyAlarmSumPage(dailyAlarmPage);
      alarmSumInitFunc();
      //停止声音
      stopSound();
      // socketAlarmHandle(alarmId);
      // smokeAlarmDataAjax();
      newAlarmFn();
    }
    // 设备添加
    if (cmd == "cmd_AddDevice") {
      var devCode = strs[1];
      var status = strs[2];
      var statusStr = strs[3];
      var latitude = strs[4];
      var longitude = strs[5];
      var deviceName = strs[6];
      var address = strs[7];
      var returntime = strs[8];
      var linkMain1 = strs[9] ? strs[9] : '';
      var linkPhone1 = strs[10] ? strs[10] : '';
      var linkMain2 = strs[11] ? strs[11] : '';
      var linkPhone2 = strs[12] ? strs[12] : '';
      var linkMain3 = strs[13] ? strs[13] : '';
      var linkPhone3 = strs[14] ? strs[14] : '';
      var linkMain4 = strs[15] ? strs[15] : '';
      var linkPhone4 = strs[16] ? strs[16] : '';
      var alarmId = strs[17];
      var fireCount = strs[18];

      var cameraUrl = strs[19];
      var streamServer = strs[20];
      var urrentMarginThreshold = strs[21];
      var temperatureThreshold = strs[22];
      var waterGage = strs[23];
      var waterLevel = strs[24];
      var chargingInterfaceNumber = strs[25];
      var deviceTypeId = strs[26];
      var orgName = strs[27];
      var numberOfChargedVehicles = strs[28];
      var userOrgId = strs[29];
      console.log(localStorage.getItem('userOrgId'), userOrgId);
      // if (localStorage.getItem('userOrgId') == userOrgId) {
      scoketDevMapShowFunc(deviceTypeId, cameraUrl, streamServer, waterGage, chargingInterfaceNumber, numberOfChargedVehicles, orgName, fireCount, status, devCode, deviceName, address, latitude, longitude, linkMain1, linkPhone1, linkMain2, linkPhone2, linkMain3, linkPhone3, linkMain4, linkPhone4);
      // }
    }
    if (cmd == 'cmd_ThreeColorWarning') {
      var unit = strs[1];
      var appearPeople = strs[2];
      var latitude = strs[3];
      var longitude = strs[4];
      var address = strs[5];
      var orgName = strs[6];
      var manager = strs[7];
      var telephone = strs[8];
      var levelisk = strs[9];
      var appearTime = strs[10];
      var areaGrid = strs[11];
      var onlyValue = strs[12];
      var userOrgId = strs[13];
      appearTime = moment(appearTime).format('YYYY-MM-DD HH:mm:ss');
      // if (localStorage.getItem('userOrgId') == userOrgId) {
      scoketEarlyWaringMapShowFunc(unit, levelisk, manager, telephone, latitude, longitude, onlyValue, address, orgName);
      // }
    }
    // 楼长制状态改变
    if (cmd == 'cmd_Building') {
      var personalPhone = strs[1];
      var longitude = strs[2];
      var latitude = strs[3];
      var uuid = strs[4];
      var address = strs[5];
      var orgName = strs[6];
      var buildingName = strs[7];
      var id = strs[8];
      var routingTime = strs[9];
      var level1 = strs[10];
      var level2 = strs[11];
      var level3 = strs[12];
      var type = strs[13];
      var onlyValue = strs[14];
      var photoUrl = '';

      // 删除对应点位
      for (var i = 0; i < houseMasterMarker.length; i++) {
        if (houseMasterMarker[i].devCode == ('houseMaster' + id)) {
          houseMasterMarker[i].removePoint();
        }
      }
      // 渲染新点位:如果地图页面在楼长制则显示点位，否则隐藏
      if (devTypeId == 'houseMaster') {
        houseMasterMarker.push(BaiDuMap.houseMasterAddMarker(type, personalPhone, '', longitude, latitude, 'houseMaster' + id, address, orgName, buildingName, id, uuid, routingTime, level1, level2, level3, photoUrl, onlyValue));
        for (var i = 0; i < houseMasterMarker.length; i++) {
          if (houseMasterMarker[i].devCode == ('houseMaster' + id)) {
            houseMasterMarker[i].showOver();
          }
        }

      } else {
        houseMasterMarker.push(BaiDuMap.houseMasterAddMarker(type, personalPhone, '', longitude, latitude, 'houseMaster' + id, address, orgName, buildingName, id, uuid, routingTime, level1, level2, level3, photoUrl, onlyValue));
        for (var i = 0; i < houseMasterMarker.length; i++) {
          if (houseMasterMarker[i].devCode == ('houseMaster' + id)) {
            houseMasterMarker[i].hideOver();
          }
        }
      }

      // 地图筛选点位气泡数量：正常、异常
      var houseMasterNumRet = getStateQuantityOfBuildings();
      houseMasterNumRet.then(function (res) {
        console.log(res);
        if (res.status == 200) {
          $('#heightPointPosition-houseMaster .tip').text(res.data.redCount);
          $('#commonlyPointPosition-houseMaster .tip').text(res.data.normalCount);
          $('#middlePointPosition-houseMaster .tip').text(res.data.yellowCount);
        }
      }).catch(function (err) {
        console.log(err);
      });
    }
  },
  onreconnect: e => console.log('Reconnecting...', e),
  onmaximum: e => console.log('Stop Attempting!', e),
  onclose: e => console.log('Closed!', e),
  onerror: e => console.log('Error:', e)
});